#!/usr/bin/python
# io2c.py
import sys

usage = '''usage: io2c ObjectName ParseFunctionName ioFile1 ioFile2 ...
output is sent to standard output
ParseFunctionName is either IoState_on_doCString_withLabel_ or IoState_on_doPackedCString_withLabel_

'''


def QuoteStream(inStr):
    outStr = '"'
    for c in inStr:
        if c == '\\' or c == '"':
            outStr += '\\'

        if c == '\n':
            outStr += '\\n"\n  \t"'
        elif c == '\r':
            outStr += '\\r"\r  \t"'
        else:
            outStr += c

    print outStr + '";\n'


def ProcessFile(ObjectName, fileName, parseFunctionName):
    fp = open(fileName, 'r')
    if fp is None:
        print 'unable to open input file', fileName
        exit(-1)

    print '\ts =',

    QuoteStream(fp.read())

    print "\tIoState_rawOn_doCString_withLabel_(self, context, s, \"%s\");\n" % fileName

    fp.close()


def main():
    if len(sys.argv) < 4:
        print usage
        return

    objectName = sys.argv[1]
    parseFunctionName = sys.argv[2]

    print '#include "IoState.h"'
    print '#include "IoObject.h"\n'
    print 'void Io' + objectName + 'Init(IoObject *context)\n{'
    print '\tIoState *self = IoObject_state((IoObject *)context);'
    print '\tchar *s;\n'

    for fileName in sys.argv[3:]:
        ProcessFile(objectName, fileName, parseFunctionName)

    print "}\n"


if __name__ == '__main__':
    main()
